package com.jinyi.wwdeng.autodialer.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import com.jinyi.wwdeng.autodialer.R
import com.jinyi.wwdeng.autodialer.data.CallTask
import com.jinyi.wwdeng.autodialer.data.CallTaskEntity
import com.jinyi.wwdeng.autodialer.databinding.ActivityMainBinding
import com.jinyi.wwdeng.autodialer.http.HttpApi
import com.jinyi.wwdeng.autodialer.http.HttpCallback
import com.jinyi.wwdeng.autodialer.http.HttpUtil
import com.jinyi.wwdeng.autodialer.manager.DialerManager
import com.jinyi.wwdeng.autodialer.manager.TimerManager
import com.jinyi.wwdeng.autodialer.repository.CallRepository
import com.jinyi.wwdeng.autodialer.ui.adapter.CallRecordAdapter
import com.jinyi.wwdeng.autodialer.utils.AppConfig
import com.jinyi.wwdeng.autodialer.utils.CallRecorderUtil
import com.jinyi.wwdeng.autodialer.utils.CallStateHelper
import com.jinyi.wwdeng.autodialer.utils.PermissionsUtil
import com.jinyi.wwdeng.autodialer.utils.TitleBarUtil
import com.jinyi.wwdeng.autodialer.utils.WavPlayer
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File


/**
 * Git Bash zip 命令：
 * 在ADModule目录下：zip -r ADModule.zip .
 */
class MainAct: BaseAct(),TimerManager.TimerCallback {
    private lateinit var binding: ActivityMainBinding
    val REQUEST_PERMISSIONS = 1001

    //定时器
    private lateinit var taskTimer: TimerManager
    //数据管理
    private lateinit var repository: CallRepository
    //通话管理
    private lateinit var dialerManager: DialerManager
    //通话状态监听
    private lateinit var callStateHelper: CallStateHelper
    //号码列表
    private var callRecordAdapter: CallRecordAdapter? = null
    //当前号码
    private var currentNumber: CallTaskEntity? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        TitleBarUtil.setStatusBarColor(this,"#FFFFFFFF".toColorInt())
        TitleBarUtil.setStatusBarLightMode(this,true)
        binding.mainParentLayout.setPadding(32, TitleBarUtil.getStatusBarHeight()+16,32,0)
        binding.txtUserName.text = AppConfig.userName.ifEmpty { getString(R.string.app_name) }

        initCallState()
        initComponents()
        initListeners()
    }

    override fun onResume() {
        super.onResume()
        updateUI()
    }

    private fun initComponents() {
        if (!checkAndRequestPermissions()) {
            return
        }
        taskTimer = TimerManager()
        repository = CallRepository.getInstance(this)
        dialerManager = DialerManager.getInstance(this)
        CallRecorderUtil.init()
    }

    /**
     * 初始化通话状态监听
     */
    private fun initCallState(){
        if (!checkAndRequestPermissions()) {
            return
        }
        // 初始化通话状态监听器
        callStateHelper = CallStateHelper(this)
        // 设置监听回调
        val callStateListener = object : CallStateHelper.CallStateListener {
            override fun onCallStateIdle() {
                // 空闲状态
                Log.e("TAG",">>>>>>>>>>>>>通话状态: 空闲中")
                updatePhoneNumberStatusDialSuccess()
            }
            override fun onCallStateRinging() {
                // 响铃状态
                Log.e("TAG",">>>>>>>>>>>>>通话状态: 来电响铃中")
            }
            override fun onCallStateOffHook() {
                // 通话中
                Log.e("TAG",">>>>>>>>>>>>>通话状态: 通话中")
                //更新通话状态为通话中
                updatePhoneNumberStatusDialing()
            }
        }
        callStateHelper.startListening(callStateListener)
    }

    private fun initListeners() {
        //启动拨号服务
        binding.btnStartService.setOnClickListener {
            if (checkAndRequestPermissions()) {
                startDialerService()
            }
        }
        //停止拨号服务
        binding.btnStopService.setOnClickListener {
            stopDialerService()
        }
        binding.btnClear.setOnClickListener {
            clearAllData()
        }
    }

    /**
     * 检查权限
     */
    private fun checkAndRequestPermissions(): Boolean {
        val missingPermissions = mutableListOf<String>()

        if (!PermissionsUtil.hasCallPermission(this)) {
            missingPermissions.add(Manifest.permission.CALL_PHONE)
        }

        if (!PermissionsUtil.hasPhoneStatePermission(this)) {
            missingPermissions.add(Manifest.permission.READ_PHONE_STATE)
        }

        if (!PermissionsUtil.hasRecordAudioPermission(this)) {
            missingPermissions.add(Manifest.permission.RECORD_AUDIO)
        }

        if (!PermissionsUtil.hasAudioOutputPermission(this)){
            missingPermissions.add(Manifest.permission.CAPTURE_AUDIO_OUTPUT)
        }

        if (!PermissionsUtil.hasIncallExperiencePermission(this)){
            missingPermissions.add("android.permission.CONTROL_INCALL_EXPERIENCE")
        }

        return if (missingPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, missingPermissions.toTypedArray(), REQUEST_PERMISSIONS)
            false
        } else {
            true
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSIONS) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (allGranted) {
                initCallState()
                initComponents()
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "需要权限才能运行自动拨号", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 更新号码状态：通话中
     */
    private fun updatePhoneNumberStatusDialing(){
//        try {
//            lifecycleScope.launch {
//                currentNumber?.let { number ->
//                    number.status = CallTaskEntity.DIAL_DIALING
//                    number.callStartTime = System.currentTimeMillis()
//                    repository.updatePhoneNumber(number.copy(status = CallTaskEntity.DIAL_DIALING, callStartTime = System.currentTimeMillis()))
//                }
//            }
//            //开始录音
//            startRecording()
//        } catch (e: Exception) {
//            Toast.makeText(this@MainAct, "更新号码状态为通话中，失败: ${e.message}", Toast.LENGTH_SHORT).show()
//        }
//        //更新UI
//        updateUI()
    }

    /**
     * 更新号码状态：成功
     */
    private fun updatePhoneNumberStatusDialSuccess(){
//        try {
//            //停止录音
//            stopRecording()
//        } catch (e: Exception) {
//            lifecycleScope.launch {
//                Toast.makeText(this@MainAct, "更新号码状态为成功，失败: ${e.message}", Toast.LENGTH_SHORT).show()
//                currentNumber?.let { number ->
//                    number.status = CallTaskEntity.DIAL_FAILED
//                    number.callEndTime = System.currentTimeMillis()
//                    repository.updatePhoneNumber(number.copy(status = CallTaskEntity.DIAL_FAILED, callEndTime = System.currentTimeMillis()))
//                }
//            }
//        }
//        //更新UI
//        updateUI()
    }

    /**
     * 处理拨号失败
     */
    private suspend fun handleDialFailure(){
//        try {
//            currentNumber?.let { phoneNumber ->
//                //重试
//                val updatedNumber = if (phoneNumber.retryCount < 3) {
//                    //状态更新为待拨号
//                    phoneNumber.copy(retryCount = phoneNumber.retryCount + 1, status = CallTaskEntity.DIAL_PENDING)
//                } else {
//                    //状态更新为失败
//                    phoneNumber.copy(status = CallTaskEntity.DIAL_FAILED)
//                }
//                repository.updatePhoneNumber(updatedNumber)
//                currentNumber = null
//                //更新UI
//                updateUI()
//            }
//        } catch (e: Exception) {
//            Log.e("AutoDialerService", "处理拨号失败时发生错误: ${e.message}")
//        }
    }

    /**
     * 启动拨号服务
     */
    private fun startDialerService() {
        if (taskTimer.isTimerRunning()){
            return
        }
        taskTimer.startTimer(
            10 , //10秒回调一次
            this
        )
        Toast.makeText(this, "自动拨号服务已启动", Toast.LENGTH_SHORT).show()
        updateUI()
    }

    /**
     * 停止拨号服务
     */
    private fun stopDialerService() {
        if (taskTimer.isTimerRunning()){
            taskTimer.stopTimer()
        }
        Toast.makeText(this, "自动拨号服务已停止", Toast.LENGTH_SHORT).show()
        updateUI()
    }

    /**
     * 获取电话号码
     */
    private suspend fun fetchNumbersManually() {
//        try {
//            //从接口获取号码
//            val data = repository.fetchPhoneNumbersFromApi()
//            if (data != null) {
//                val number = data.optString("mobile","")
//                if (number.isEmpty()){
//                    return
//                }
//                val item = CallTaskEntity(
//                    phoneNumber = number,
//                    product = data.optString("product"),
//                    orderId = data.optString("orderId"),
//                    mobileType = data.optString("mobileType"),
//                    userId = data.optString("userId")
//                )
//                val insertedCount = repository.insertPhoneNumber(item)
//                Log.e("TAG","成功获取 $insertedCount 个号码")
//                updateUI()
//
//                //待拨号码
//                val pendingNumber = repository.getPendingNumber()
//                pendingNumber?.let {
//                    startCallAction(pendingNumber)
//                }
//            } else {
//                showToast("no new number")
//            }
//        } catch (e: Exception) {
//            Log.e("TAG","获取号码失败: ${e.message}")
////            Toast.makeText(this@MainActV2, "获取号码失败: ${e.message}", Toast.LENGTH_SHORT).show()
//        }
    }

    /**
     * 清空数据
     */
    private fun clearAllData() {
        AlertDialog.Builder(this)
            .setTitle("确认清空")
            .setMessage("确定要清空所有号码数据吗？")
            .setPositiveButton("确定") { dialog, which ->
                try {
                    repository.clearAllNumbers(callback = {
                        Toast.makeText(this@MainAct, "数据已清空", Toast.LENGTH_SHORT).show()
                        updateUI()
                    })
                } catch (e: Exception) {
                    Toast.makeText(this@MainAct, "清空数据失败", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 开始录音
     */
    private fun startRecording(){
        try {
            currentNumber?.let { number ->
                val started = CallRecorderUtil.startRecording(this,number.phoneNumber)
            }
        } catch (e: Exception){
            Log.e("TAG","${currentNumber?.phoneNumber} start record error: ${e.message}")
        }
    }

    /**
     * 停止录音
     */
    private fun stopRecording(){
//        try {
//            lifecycleScope.launch {
//                currentNumber?.let { number ->
//                    val wavPath = CallRecorderUtil.stopRecording()
//                    Log.e("TAG",">>>>>录音文件 wav 路径>>>>>>>>>>>>>>>>>>>>>${wavPath}")
//
//                    //延时500毫秒查询记录，避免通话记录数据库未更新
//                    delay(500)
//                    val callLog = CallLogUtil.read(MyApplication.instance, number.phoneNumber)
//                    Log.e("TAG",">>>>>${number.phoneNumber} log >>>>>>>>>>>>>>>>>>>>>${callLog}")
//
//                    //状态为成功
//                    if (number.status == CallTaskEntity.DIAL_DIALING) {
//                        number.status = CallTaskEntity.COMPLETED
//                        number.callEndTime = System.currentTimeMillis()
//                        number.localAudioPath = wavPath
//                        number.callLog = callLog
//                        //更新状态为成功，更新结束通话时间，更新录音文件本地路径，更新通话记录信息
//                        repository.updatePhoneNumber(number.copy(status = CallTaskEntity.COMPLETED, callEndTime = System.currentTimeMillis(), localAudioPath = wavPath, callLog = callLog))
//                    }
//                    //上传录音文件
//                    uploadWavFile()
//                }
//            }
//        } catch (e: Exception){
//            Log.e("TAG","${currentNumber?.phoneNumber} stop record error: ${e.message}")
//        }
    }

    /**
     * 更新UI
     */
    @SuppressLint("SetTextI18n")
    private fun updateUI() {
        lifecycleScope.launch {
            try {
                //待拨号码数量
                val pendingCount = repository.getPendingCount()
                //所有号码列表
                val phoneNumberList = repository.getAllNumbers()

                //服务是否运行中
                val isRunning = taskTimer.isTimerRunning()
//                binding.tvStatus.text = "服务状态: ${if (isRunning) "运行中" else "已停止"}"
//                binding.tvPendingCount.text = "待拨号码: $pendingCount"
//                binding.tvCurrentNumber.text = "当前号码: ${if (currentNumber == null) "无" else "${currentNumber?.phoneNumber}"}"
//                binding.tvPhoneState.text = "通话状态: ${if (callStateHelper.isInCall()) "通话中" else "空闲中"}"

                // 更新按钮状态
                binding.btnStartService.isEnabled = !isRunning
                binding.btnStopService.isEnabled = isRunning

                //刷新号码列表
                updateNumberList(phoneNumberList)
            } catch (e: Exception) {
                Log.e("MainActivity", "更新UI失败: ${e.message}")
            }
        }
    }

    /**
     * 更新号码列表
     */
    @SuppressLint("SetTextI18n")
    private fun updateNumberList(numberList: List<CallTaskEntity>){
//        if (callRecordAdapter == null){
//            binding.recyclerView.setHasFixedSize(true)
//            binding.recyclerView.isNestedScrollingEnabled = false
//            binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
//            val layoutManager = LinearLayoutManager(this)
//            binding.recyclerView.layoutManager = layoutManager
//            callRecordAdapter = CallRecordAdapter(numberList.toMutableList(), onClickPlay = {view , _, model ->
//                when(view.id){
//                    R.id.tvInfo -> {
//                        //拨号
//                        Log.e("TAG","拨号>>>>>>>>>>>>>${model.phoneNumber}")
//                        lifecycleScope.launch {
//                            startCallAction(model)
//                        }
//                    }
////                    R.id.tvInfo -> {
////                        Log.e("TAG","播放录音>>>>>>>>>>>>>${model.phoneNumber},${model.audioPath}")
////                        val wavFile = File(model.audioPath)
////                        WavPlayer.play(this, wavFile) {
////                            Log.d("Test", "播放完成")
////                        }
////                    }
//                }
//            })
//            binding.recyclerView.adapter = callRecordAdapter
//            return
//        }
//        callRecordAdapter?.updateData(numberList.toMutableList())
    }

    /**
     * 开始拨号
     */
    @SuppressLint("SetTextI18n")
    private suspend fun startCallAction(pendingNumber: CallTask){
//        // 检查系统通话状态
//        if (callStateHelper.isInCall()){
//            Log.e("TAG", "系统检测到通话状态：通话中，等待空闲状态")
//            binding.tvPhoneState.text = "通话状态: 通话中"
//            return
//        }
//        //存在处理中的号码
//        if (currentNumber != null){
//            return
//        }
//        currentNumber = pendingNumber
//        binding.tvCurrentNumber.text = "当前号码: ${pendingNumber.phoneNumber}"
//        val dialSuccess = dialerManager.dialNumberV2(pendingNumber)
//        //拨号失败
//        if (!dialSuccess){
//            handleDialFailure()
//        }
    }

    /**
     * 计时器每秒回调一次
     */
    @SuppressLint("SetTextI18n")
    override fun onTickSecond(second: Int) {
        //服务是否运行中
        val isRunning = taskTimer.isTimerRunning()
//        binding.tvStatus.text = "服务状态: ${if (isRunning) "运行中" else "已停止"}(${second})"
    }

    /**
     * 计时器 指定 10s 回调一次
     */
    override fun onTimerIntervalReached() {
        // 检查系统通话状态
//        if (callStateHelper.isInCall()){
//            Log.e("TAG","正在通话中>>>>>>>>>")
//            binding.tvPhoneState.text = "通话状态: 通话中"
//            return
//        }
//        //更新ui
//        updateUI()
//
//        lifecycleScope.launch {
//            //待拨号码数量
//            val pendingCount =  repository.getPendingCount()
//            //待拨号码单个
//            val pendingNumber = repository.getPendingNumber()
//            //待拨号码为0，需要获取数据
//            if (pendingCount == 0 || pendingNumber == null){
//                //从接口获取
//                fetchNumbersManually()
//            } else {
//                //待拨号号码 - 开始拨号
//                startCallAction(pendingNumber)
//            }
//        }
    }

    /**
     * 上传文件
     */
    private fun uploadWavFile(){
        val wavPath = currentNumber?.localAudioPath
        if (wavPath == null){
            return
        }
        val wavFile = File(wavPath)
        if (!wavFile.isFile){
            return
        }
        Log.e("TAG",">>>>>开始上传录音 >>>>>>>>>>>>>>>>>>>>>${wavPath}")
        showLoading(false)
        currentNumber?.let { number ->
            val params = hashMapOf<String,String>().apply {
                put("sysLoginName",AppConfig.userName)
                put("token",AppConfig.userToken)
                put("mobile",number.phoneNumber)
                put("orderId",number.orderId ?: "")
                put("userId",number.userId ?: "")
                put("product",number.product ?: "")
                put("mobileType",number.mobileType ?: "")
            }
            HttpUtil.getInstance().uploadFile(context = this,
                url = HttpApi.API_UPLOAD_FILE,
                file = wavFile,
                fileParamName = "file",
                otherParams = params,
                headers = null,
                callback = object : HttpCallback{
                    override fun onSuccess(data: JSONObject) {
                        when(data.optInt("code")) {
                            0 -> {
                                val dataObj = data.optJSONObject("obj")
                                dataObj?.let {
                                    val wavUrl = dataObj.optString("url")
                                    number.serverAudioPath = wavUrl
                                    lifecycleScope.launch {
                                        //更新录音文件服务器路径
                                        repository.updatePhoneNumber(number.copy(serverAudioPath = wavUrl))
                                    }
                                    updateUI()
                                    subNumberCallInfo()
                                }
                            }
                        }
                        Log.e("TAG",">>>>>上传录音文件完成 >>>>>>>>>>>>>>>>>>>>>${data}")
                    }
                    override fun onFailure(error: String) {
                    }
                    override fun onFinish() {
                        hideLoading()
                    }
                })
        }
    }

    /**
     * 保存号码信息
     */
    private fun subNumberCallInfo(){
        currentNumber?.let { number ->
            val body = JSONObject().apply {
                put("sysLoginName",AppConfig.userName)
                put("token",AppConfig.userToken)
                put("mobile",number.phoneNumber)
                put("orderId",number.orderId ?: "")
                put("userId",number.userId ?: "")
                put("product",number.product ?: "")
                put("mobileType",number.mobileType ?: "")
                put("url",number.serverAudioPath ?: "")
                put("callRecord",number.callLog ?: "")
            }
            post(HttpApi.API_SAVE_NUMBER_RECORD, body,null,object : HttpCallback{
                override fun onSuccess(data: JSONObject) {
                    currentNumber = null
                }
                override fun onFailure(error: String) {
                }
                override fun onFinish() {
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        taskTimer.stopTimer()
        repository.shutdown()
        CallRecorderUtil.release()
        WavPlayer.stop()
        callStateHelper.release()
        currentNumber = null
    }
}